<?php
namespace app\ba\controller;

use think\Config;
use think\Controller;
use think\Db;
use think\Session;

/**
 * 后台登录
 * Class Login
 * @package app\admin\controller
 */
class Login extends Controller
{
    /**
     * 后台登录
     * @return mixed
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 登录验证
     * @return string
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->only(['username', 'password', 'verify']);
            $validate_result = $this->validate($data, 'Login');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $where['username'] = $data['username'];
                $where['password'] = md5($data['password'] . Config::get('salt'));

                $admin_user = Db::name('user')->field('id,username,status,roleid,nickname')->where($where)->find();
                if (!empty($admin_user)) {
                    if ($admin_user['status'] != 1) {
                        $this->error('当前用户已禁用');
                    } else {
                        //判断角色是否正确
                        if ( $admin_user['roleid'] != 8){
                            $this->error('您不是经营分析');
                        }else{
                            Session::set('ba_id', $admin_user['id']);
                            Session::set('ba_name', $admin_user['nickname']);
                            Db::name('user')->update(
                                [
                                    'last_login_time' => date('Y-m-d H:i:s', time()),
                                    'last_login_ip'   => $this->request->ip(),
                                    'id'              => $admin_user['id']
                                ]
                            );

                            $controllerName = request()->module();
                            $url = $controllerName . '/index/index';
                            $this->success('登录成功', $url);
                        }
                    }
                } else {
                    $this->error('用户名或密码错误');
                }
            }
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Session::delete('ba_id');
        Session::delete('ba_name');
        $controllerName = request()->module();
        $url = $controllerName . '/login/index';
        $this->success('退出成功', $url);
    }
}
